package com.song.mall.product.web;

import com.song.mall.product.entity.CategoryEntity;
import com.song.mall.product.service.CategoryService;
import com.song.mall.product.vo.Catelog2Vo;
import org.bouncycastle.math.raw.Mod;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/9/15 - the current system date.
 * 17:53 - the current system time.
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;


    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //TODO 查出所有的一级分类
        List<CategoryEntity> categoryEntities  = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }


    @ResponseBody
    @GetMapping("index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        //System.out.println("-----------------------------------------");
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }


    /**
     *  信号量（Semaphore）
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.acquire();
        return "ok";
    }

    @ResponseBody
    @GetMapping("/go")
    public String go(){
        RSemaphore park = redisson.getSemaphore("park");
        park.release();
        return "ok";
    }


    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //获取一把锁 只要名字一样 加锁同一把锁
        RLock lock = redisson.getLock("my-lock");
        //加锁
        lock.lock();
        try {
            Thread.sleep(30000);
            System.out.println("加锁成功 执行业务");
        }catch (Exception e){

        } finally {
            //解锁
            System.out.println("释放锁");
            lock.unlock();
        }

        return "hello";
    }
}
